package org.itboys.weixin.service;

import com.google.common.collect.Maps;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.weixin.entity.WeixinMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 微信消息相关
 * @author ChenJunhui
 *
 */
@Service
public class WeixinMessageService extends BaseWeixinService<WeixinMessage, Long> {

	private static final long serialVersionUID = 6677086354468603767L;
	
	@Autowired
	private WeixinMessageKeywordService weixinMessageKeywordService;
	
	@Resource(name="weixinDS")
	private MongoDataSource weixinMessageDataSource;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return weixinMessageDataSource;
	}

	@Override
	protected Class<WeixinMessage> getEntityClass() {
		return WeixinMessage.class;
	}
	
	public void save(WeixinMessage detail){
		detail.setCreateTime(new Date());
		detail.setCreator(AdminSessionHolder.getAdminUserId());
		super.save(detail);
	}
	
	public void update(WeixinMessage detail){
		WeixinMessage detail2 = getById(detail.getId());
		detail.setCreateTime(detail2.getCreateTime());
		detail.setCreator(detail2.getCreator());
		detail.setUpdater(AdminSessionHolder.getAdminUserId());
		detail.setUpdateTime(new Date());
		super.update(detail);
	}
	
	public WeixinMessage getWxmsgByKeywordAndWeixinId(Long weixinId, String keyword){
		Long wxMsgId=weixinMessageKeywordService.getMsgIdByKeywordAndWeixinId(keyword, weixinId);
		if(null!=wxMsgId){
			WeixinMessage weixinMessage=super.getById(wxMsgId);
			return weixinMessage;
		}
		return null;
	}
	//获取默认微信信息  type=1默认  值存在则唯一
	public WeixinMessage getDefaultMsgByWeixinId(Long weixinId){
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(2);
		param.put("weixinId", weixinId);
		param.put("type", 1);
		List<WeixinMessage> list = list(param);
		return list!=null&&!list.isEmpty()?list.get(0):null;
	}
	
}
